/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.cloud.header.servlet;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;

import com.iiifi.kite.boot.utils.WebUtils;
import com.iiifi.kite.cloud.header.KiteHttpHeaders;
import com.iiifi.kite.core.util.StringUtils;
import com.iiifi.kite.configuration.KiteProperties;

import lombok.AllArgsConstructor;

/**
 * HttpHeaders 获取器
 *
 * @author kite@iiifi.com 花朝
 */
@Configuration
@AllArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ServletHttpHeadersGetter implements KiteHttpHeaders {

    private KiteProperties kiteProperties;

    @Nullable
    @Override
    public HttpHeaders get() {
        HttpServletRequest request = WebUtils.getRequest();
        if (request == null) {
            return null;
        }
        // 设置向下传递的请求头
        HttpHeaders headers = new HttpHeaders();
        // 设置appName
        headers.add(kiteProperties.getHeaders().getAppName(), kiteProperties.getName());
        // 将需要向下传递的请求头设置到请求header中
        List<String> allowHeadsList = kiteProperties.getAllowHeads();
        for (String key : allowHeadsList) {
            String value = request.getHeader(key);
            if (StringUtils.isNotBlank(value)) {
                headers.add(key, value);
            }
        }
        return headers.isEmpty() ? null : headers;
    }
}
